<template>
  <view class="navigation">
    <eui-navbar ref="EuiNavBar" title="群组成员" displayable="true" color="#000000" backgroundColor="#FFFFFF"
                rightIcon="" rightText="解散群组" :showPopup="false" @clickRight="dissolveGroup"/>
    <view class="main-view" :style="{ height: scrollHeight + 'rpx' }">
      <scroll-view scroll-y="true" style="height: 100%;">
        <eui-card title="" topMargin="0">
          <view v-if="groupList.length > 0" class="item-view" v-for="(item, index) in groupList" :key="index" @click="itemClick">
            <view class="icon-view">
              <image :src="item.userIcon" @error="setErrorImg(item)" class="border-radius-50"
                     style="width: 72rpx;height: 72rpx;"></image>
            </view>
            <view class="name-view">
              <text>{{ item.Name }}</text>
            </view>
            <view class="right-view" @click="removePerson(item)">
              <text style="margin-right: 10rpx">移出群组</text>
              <eui-uicons type="right" size="24" color="#888888" />
            </view>
          </view>
          <view v-else>
            <image src="@/static/img/no_data.png" mode="aspectFit" class="image-min" />
            <view class="no-data-text">暂无任何成员</view>
          </view>
          <view class="item-view add-view" :class="[theme]" @click="addPerson">
            <text>添加成员</text>
          </view>
        </eui-card>
      </scroll-view>
    </view>
  </view>
</template>

<script setup type="ts">
import { storeToRefs } from 'pinia';
import {computed, onMounted, ref} from "vue";
import {onLoad} from "@dcloudio/uni-app";
import {getRdsSysConfig, init} from "@/hooks/init";
import { getRelatedName, getDictName, getUserDictSelectList, getDictSelect, getDictSelectList, getWeightUnits, getDictList } from '../../components/RelatedName.js';
import Enjoy from "@/common/enjoy";
import { getRdsUrl, rdsRequest } from "@/hooks/rdsServices";
import {useMainStore} from "@/store/modules/store";
import {useLoginStore} from "@/store/modules/useLoginStore";
import TaskGround from '../components/taskGroup.vue'
import Guid from '@/common/guid';
import service from "@/common/service";
import useService from '@/hooks/useService';
import useUpload from "@/hooks/useUpload";
import { useThemeStore } from '@/store/themeStore';
const themeStore = useThemeStore(); // 主题
const { theme } = storeToRefs(themeStore);

const mainService = useService({ prefix: "mainApi" });
const { upload, remove, fetchFile } = useUpload({ prefix: 'mainApi' });
const rdsUrl = getRdsUrl();
const mainStore = useMainStore();
const { loginInfo } = mainStore;
const LoginStore = useLoginStore();

const scrollHeight = ref(0);
// 群组成员
const groupList = ref([
  // { Name: '名称1', UserNo: '0389' },
  // { Name: '名称2', UserNo: '0003' },
  // { Name: '名称3', UserNo: '03892' },
  // { Name: '名称4', UserNo: '03893' },
  // { Name: '名称5', UserNo: '03894' },
]);
const roleCode = ref('');
const roleClassCode = ref('');


// 获取列表高度
const getListHeight = async () => {
  await uni.getSystemInfo({
    success: function (res) {
      let info = uni.createSelectorQuery().select(".main-view");
      info.boundingClientRect(function (data) {
        //获取列表高度
        let height = res.windowHeight - data.top;
        //转换rpx
        scrollHeight.value = height / (res.windowWidth / 750) - 20;
      }).exec()
    }
  });
};

onMounted((e) => {
  getListHeight()
});

onLoad(async (e) => {
  roleCode.value = e.code;
  roleClassCode.value = e.classCode;
  await getGroupRoles();
})

// 成员头像
const setUserPic = (e) =>{
  let pic = '';
  const imgUrl = LoginStore.EnjoyMain.replace('/Enjoy/Service', '');
  pic = imgUrl + '/File/DownLoadImage/' + e;
  return pic
}

const setErrorImg = (e) => {
  e.userIcon = '/static/img/noUserImg.png';
}

// 获取当前群组下的成员
const getGroupRoles = async () => {
  service.enjoyShowLoading('加载中..');
  const result = await rdsRequest(rdsUrl.mainApi, 'taskdefine', 'FetchUsersOfTaskRoles', roleCode.value);
  if (result && result.length > 0) {
    groupList.value = result.map(obj => {
      return {
        ...obj,
        userIcon: setUserPic(obj.UserNo)
      }
    })
  }
  service.enjoyHideLoading();
}

// 解散群组
const dissolveGroup = () => {
  uni.showModal({
    title: ' 提示',
    content: '您真的要解散该群组吗？',
    showCancel: true,
    success: async (res) => {
      if (res.confirm) {
        service.enjoyShowLoading('正在处理...');
        let req = {
          RoleCode: roleCode.value,
          RoleTypeCode: roleClassCode.value,
        }
        const result = await rdsRequest(rdsUrl.mainApi, 'h5Role', 'DeleteRoleItem', req);
        service.enjoyHideLoading();
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: ' 解散成功'
        });
        // 返回并刷新
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 2];
        uni.navigateBack({
          delta: 1,
          success: () => {
            if (prevPage && prevPage.$vm) {
              setTimeout(() => {
                prevPage.$vm.$.exposed.updateGroupList();
              }, 500);
            } else {
              console.error('Error: Previous page or method not found.');
            }
          },
          fail: (error) => {
            console.error('Navigation failed:', error);
          }
        });
      }
    }
  });
}

// 弹框取消
const popupCancel = () => {

}

// 弹框确认
const popupConfirm = () => {

}

// 移除成员
const removePerson = (item) => {
  uni.showModal({
    title: '提示',
    content: `确定将[${item.Name}]移出群组吗?`,
    showCancel: true,
    success: (res) => {
      if (res.confirm) {
        fetchUserRoles(item.UserNo);
      }
    }
  });
}

// 确定移出群组
const fetchUserRoles = async (userId) =>{
  uni.showLoading({ title: "处理中...", mask: true });
  // 当前用户的所有角色
  const oriList = await mainService.request('h5UserGroup', 'FetchUserRoles', userId);
  // 更新当前用户的角色
  let newList = oriList.filter(x=>x.Code != roleCode.value);
  const req =  {
    UserNo: [userId],
    RoleItems: newList,
    isOverwrite: true,
  }
  const res = await mainService.request('h5UserGroup', 'UpdateUserRols', req);
  // 更新列表
  groupList.value = groupList.value.filter(x=>x.UserNo != userId);
  uni.hideLoading();
}

// 添加成员
const addPerson = () => {
  let parms = Enjoy.GetDialogParms();
  parms.CallBack = SelectionChangedUser;
  parms.SelectionType = "人员选择";
  Enjoy.OpenDialog(parms)
}

const SelectionChangedUser = async (event) => {
  let { Key, Value } = event.BackParms;
  let item = groupList.value.find(x => x.UserNo === Key);
  if (item) {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: `人员 [${Key}]${Value} 已在当前群组!`,
      mask: true,
    });
    return
  }
  // 当前用户的所有角色
  const list = await mainService.request('h5UserGroup', 'FetchUserRoles', Key);
  // 更新当前用户的角色
  list.push({
    RoleClass: roleClassCode.value,
    Code: roleCode.value,
  })
  const req =  {
    UserNo: [Key],
    RoleItems: list,
    isOverwrite: true,
  }
  const res = await mainService.request('h5UserGroup', 'UpdateUserRols', req);
  // 更新列表
  groupList.value.push({
    Name: Value,
    UserNo: Key,
    userIcon: setUserPic(Key)
  });
}

// 点击单个item
const itemClick = (item, index) => {
  console.log('======点击单个item: ', item);
}

</script>

<style lang="scss" scoped>
@import '@/main.scss';

.navigation {
  display: flex;
  height: 100vh;
  width: 100%;
  flex-direction: column;
  background: #F2F2F2;
}

.main-view {
  width: 100%;
  margin-top: 20rpx;
  display: flex;
  position: relative;
}

.item-view {
  width: 100%;
  height: 100rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  border-bottom: 1rpx solid $uni-line-color;
  align-items: center;

  .icon-view {
    width: 72rpx;
    height: 72rpx;
    margin-right: 20rpx;
    border-radius: 36rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
  }
  .border-radius-50 {
    border-radius: 50%;
  }
  .name-view {
    flex: 1;
    font-weight: $uni-font-weight-level1;
    font-size: $uni-font-size-level3;
    color: $uni-text-color-primary;
    line-height: 39rpx;
  }
}

.right-view {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  font-family: $uni-font-family;
  font-weight: $uni-font-weight-level1;
  font-size: $uni-font-size-level7;
  color: $uni-text-color-hint;
  line-height: 28rpx;
  font-style: normal;
}

.add-view {
  display: flex;
  height: 70rpx;
  margin-bottom: 10rpx;
  justify-content: center;
  align-items: flex-end;
  font-weight: $uni-font-weight-level1;
  font-size: $uni-font-size-level3;
  color: var(--theme-color);
  border-bottom: 0;
  line-height: 39rpx;
}

.image-min {
  width: 100%;
  height: 150rpx;
  opacity: 0.6;
  margin-top: -40rpx;
}

.no-data-text {
  text-align: center;
  color: #cccccc;
  font-size: 24rpx;
  margin-top: -10rpx;
  margin-bottom: 20rpx;
}

</style>
